﻿using System;
using System.Diagnostics;
using System.Runtime.Serialization;

namespace RockBus.Monitoring.DataContracts
{
    /// <summary>
    /// Specifies the value for the collected performance counter (instance) value.
    /// </summary>
    [DataContract(Namespace = NamespaceConstants.MonitoringNamespace)]
    public class PerformanceCounterInstance : ICloneable
    {
        public const string SINGLE_INSTANCE_NAME = "systemdiagnosticsperfcounterlibsingleinstance";

        private PerformanceCounterInstance()
        {
        }

        public PerformanceCounterInstance(string categoryName, string counterName, string instanceName, double value)
            : this()
        {
            this.CategoryName = categoryName;
            this.CounterName = counterName;
            if (instanceName.Equals(SINGLE_INSTANCE_NAME))
            {
                this.InstanceName = string.Empty;
            }
            else
            {
                this.InstanceName = instanceName;
            }
            this.Value = value;
        }

        /// <summary>
        /// The performance counter category name.
        /// </summary>
        [DataMember]
        public string CategoryName { get; private set; }

        /// <summary>
        /// The performance counter counter name.
        /// </summary>
        [DataMember]
        public string CounterName { get; private set; }

        /// <summary>
        /// The performance counter instance name.
        /// </summary>
        [DataMember]
        public string InstanceName { get; private set; }

        /// <summary>
        /// The performance counter (instance) value.
        /// </summary>
        [DataMember]
        public double Value { get; set; }

        public PerformanceCounterCategoryType CategoryType
        {
            get
            {
                if ((string.IsNullOrEmpty(this.InstanceName)) || (this.InstanceName.Equals(SINGLE_INSTANCE_NAME)))
                {
                    return PerformanceCounterCategoryType.SingleInstance;
                }

                return PerformanceCounterCategoryType.MultiInstance;
            }
        }

        public override string ToString()
        {
            return string.Format(@"\{0}\{1}\{2}: {3};",
                this.CategoryName,
                this.CounterName,
                this.InstanceName,
                this.Value);
        }

        #region ICloneable Members

        public object Clone()
        {
            var pci = new PerformanceCounterInstance(this.CategoryName, this.CounterName, this.InstanceName, this.Value);
            return pci;
        }

        #endregion ICloneable Members
    }
}